<template>
  <div>
    <el-card shadow="never" class="border-none">
      <div slot="header">
        <div class="flex-x gap-4 pt-2">
          <span>
            <vxe-input v-model="query.keyword" :placeholder="'搜索讲义标题'" size="medium" clearable
              @keyup.enter.native="filterByKeyword"></vxe-input>
          </span>
          <span>
            <el-button type="primary" plain size="small" @click="filterByKeyword" icon="el-icon-search"
              :loading="loading">搜索</el-button>
          </span>
          <span class="flex-1"></span>
          <span>
            <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">
              添加讲义
            </el-button>
          </span>
        </div>
      </div>

      <!-- Handout Table -->
      <vxe-table stripe auto-resize :data="handoutList" :loading="loading" align="center">
        <vxe-table-column field="id" title="ID" width="60"></vxe-table-column>
        <vxe-table-column field="title" title="讲义标题" min-width="120"></vxe-table-column>

        <vxe-table-column field="fileUrl" title="文件" min-width="200">
          <template v-slot="{ row }">
            <el-link type="primary" :href="row.fileUrl" target="_blank">{{ row.fileUrl }}</el-link>
          </template>
        </vxe-table-column>

        <vxe-table-column field="type" title="文件类型" width="100">
          <template v-slot="{ row }">
            <el-tag size="small">{{ row.type }}</el-tag>
          </template>
        </vxe-table-column>

        <vxe-table-column title="状态" width="100">
          <template v-slot="{ row }">
            <el-switch v-model="row.enabled" @change="handleStatusChange(row)" class="my-2">
            </el-switch>
          </template>
        </vxe-table-column>
        <vxe-table-column field="gmtCreate" title="创建时间" width="150">
          <template v-slot="{ row }">
            {{ formatDate(row.gmtCreate) }}
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="120" fixed="right">
          <template v-slot="{ row }">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button plain circle type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button plain circle type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(row)">
              </el-button>
            </el-tooltip>
          </template>
        </vxe-table-column>
      </vxe-table>

      <!-- Handout Dialog -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="resetForm" append-to-body
        destroy-on-close>
        <el-form :model="handoutForm" :rules="rules" ref="handoutForm" label-width="100px">
          <el-form-item label="文件" prop="fileUrl">
            <aliyun-oss-upload drag progress :show-file-list="true" type="lesson_handout" @success="handleUploadSuccess"
              class="w-full">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
            </aliyun-oss-upload>
          </el-form-item>

          <el-form-item label="讲义标题" prop="title">
            <el-input v-model="handoutForm.title" clearable placeholder="请输入讲义标题"
              @keyup.enter.native="submitForm"></el-input>
          </el-form-item>

          <el-form-item label="是否启用" prop="enabled">
            <el-switch v-model="handoutForm.enabled"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import api from '@/common/api';

import AliyunOssUpload from '@/components/admin/AliyunOssUpload.vue';
export default {
  name: 'LessonHandoutList',
  components: {
    AliyunOssUpload
  },
  props: {
    lessonId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      // List data
      handoutList: [],
      loading: false,
      query: {
        keyword: ''
      },

      // Dialog data
      dialogVisible: false,
      dialogTitle: '',
      fileList: [],
      lesson: {},
      handoutForm: {
        lessonId: this.lessonId,
        title: '',
        fileUrl: '',
        type: '',
        enabled: true
      },
      rules: {
        title: [
          { required: true, message: '请输入讲义标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ],
        fileUrl: [
          { required: true, message: '请上传文件', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getHandoutList();
  },
  methods: {
    async getHandoutList() {
      try {
        this.loading = true;
        let rsp = await api.admin_getLessonDetail(this.lessonId);
        this.lesson = rsp.data.data;
        this.handoutList = this.lesson.handoutList;

        // 通知父组件讲义数量变化
        this.$emit('count-change', this.handoutList.length);
      } finally {
        this.loading = false;
      }
    },

    handleUploadSuccess({ url, name }) {
      this.handoutForm.fileUrl = url;
      this.handoutForm.title = name.substring(0, name.lastIndexOf('.'));
    },

    handleAdd() {
      this.dialogTitle = '添加讲义';
      this.handoutForm.courseId = this.courseId;
      this.handoutForm.lessonId = this.lessonId;
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑讲义';
      this.handoutForm = { ...row };
      this.dialogVisible = true;
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该讲义?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await api.admin_deleteLessonHandout(row.id);
        this.$message.success('删除成功');
        this.getHandoutList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    async handleStatusChange(row) {
      try {
        await api.admin_saveLessonHandout({
          id: row.id,
          enabled: row.enabled
        });
        this.$message.success('状态更新成功');
      } catch (error) {
        row.enabled = !row.enabled;
        this.$message.error('状态更新失败');
      }
    },

    submitForm() {
      this.$refs.handoutForm.validate(async (valid) => {
        if (valid) {
          try {
            await api.admin_saveLessonHandout(this.handoutForm);
            this.$message.success(this.handoutForm.id ? '更新成功' : '添加成功');
            this.dialogVisible = false;
            this.getHandoutList();
          } catch (error) {
            this.$message.error(this.handoutForm.id ? '更新失败' : '添加失败');
          }
        }
      });
    },
    resetForm() {
      this.$refs.handoutForm?.resetFields();
      this.handoutForm = {
        courseId: this.courseId,
        lessonId: this.lessonId,
        title: '',
        fileUrl: '',
        type: '',
        enabled: true
      };
      this.fileList = [];
    },

    beforeUpload(file) {
      const isPPTOrPDF = file.type === 'application/pdf' ||
        file.type === 'application/vnd.ms-powerpoint' ||
        file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isPPTOrPDF) {
        this.$message.error('只能上传PPT或PDF文件!');
        return false;
      }
      if (!isLt20M) {
        this.$message.error('文件大小不能超过 20MB!');
        return false;
      }
      return true;
    },

    filterByKeyword() {
      this.query.currentPage = 1;
      this.getHandoutList();
    },

    formatDate(date) {
      return date
    }
  }
};
</script>

<style scoped>
.upload-demo {
  width: 360px;
}
</style>